/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fresh.bus.canoe.message.support;


import com.fresh.bus.canoe.message.Response;
import com.fresh.bus.canoe.message.ResponseList;
import com.fresh.bus.canoe.message.ResponseQueue;
import com.fresh.bus.canoe.session.Role;
import com.fresh.bus.canoe.session.Session;
import com.fresh.bus.canoe.session.SessionRoleManager;

import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author panzd
 */
public class DefaultResponseQueue extends Thread implements ResponseQueue{
    private static final Logger log = LoggerFactory.getLogger(ResponseQueue.class);

    private ConcurrentLinkedQueue<Response> queue;
    private SessionRoleManager sessionRoleManager;
    /**
     * @return the sessionRoleManager
     */
    public SessionRoleManager getSessionRoleManager() {
        return sessionRoleManager;
    }

    /**
     * @param sessionRoleManager the sessionRoleManager to set
     */
    public void setSessionRoleManager(SessionRoleManager sessionRoleManager) {
        this.sessionRoleManager = sessionRoleManager;
    }

    public DefaultResponseQueue()
    {
        queue = new ConcurrentLinkedQueue<Response>();
    }

    @Override
    public void add(Response response)
    {
        queue.add(response);
    }

    @Override
    public void addAll(Response[] responses)
    {
        for(Response response : responses)
        {
            queue.add(response);
        }
    }

    @Override
    public void addAll(ResponseList responses)
    {
        queue.addAll(responses);
    }

    @Override
    public void run()
    {
        for(;;)
        {
            if(isInterrupted())
            {
                return;
            }

            Response response = queue.poll();
            if(response != null)
            {
                Collection<Role> recievers = response.getRecievers();

                if(recievers == null || recievers.isEmpty())
                {
                    log.error("no recievers for " + response);
                }

                for (Role reciever : recievers) {
                    Session session = getSessionRoleManager().getSession(reciever);
                    if (session != null) {
                        session.send(response);
                        log.debug("send " + response);
                    }
                }
            }
        }
    }
}
